namespace Xmef.Serializer
{
    using System;
    using System.Deployment.Application;
    using System.IO;
    using Xmef.Interfaces;

    [Serializable]
    public class XmlFileSerializer<T> : XmlFileStreamSerializer<T>
    {
        public override bool Attach(string key)
        {
            lock (((XmlFileSerializer<T>) this))
            {
                if (ApplicationDeployment.IsNetworkDeployed)
                {
                    if (ApplicationDeployment.CurrentDeployment != null)
                    {
                        return AttachFile(Path.Combine(ApplicationDeployment.CurrentDeployment.DataDirectory, key));
                    }
                }
                else
                {
                    return AttachFile(key);
                }
                return false;
            }
        }

        protected override bool Deserialize(IXmlTypeFormatter formatter)
        {
            lock (((XmlFileSerializer<T>) this))
            {
                if (FileName != null)
                {
                    using (Stream stream = File.Open(FileName, FileMode.Open, FileAccess.Read, FileShare.None))
                    {
                        return Deserialize(stream, formatter);
                    }
                }
                return false;
            }
        }

        public override bool Detach(string key)
        {
            lock (((XmlFileSerializer<T>) this))
            {
                if (ApplicationDeployment.IsNetworkDeployed)
                {
                    if (ApplicationDeployment.CurrentDeployment != null)
                    {
                        return DetachFile(Path.Combine(ApplicationDeployment.CurrentDeployment.DataDirectory, key));
                    }
                }
                else
                {
                    return DetachFile(key);
                }
                return false;
            }
        }

        protected override bool Serialize(T obj, IXmlTypeFormatter formatter)
        {
            lock (((XmlFileSerializer<T>) this))
            {
                if (FileName != null)
                {
                    using (Stream stream = File.Open(FileName, FileMode.Create, FileAccess.Write, FileShare.None))
                    {
                        return Serialize(obj, stream, formatter);
                    }
                }
                return false;
            }
        }
    }
}

